<template>
  <ContentWrap ref="form">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="学籍号" prop="studentCode">
        <el-input
          v-model="queryParams.studentCode"
          placeholder="请输入学籍号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CMIS_GRADE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="在校状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择在校状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CMIS_STUDENT_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <cascadeSelection ref="selection" :useType="true" />
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <!-- <el-button type="primary" @click="openForm('create')" v-hasPermi="['cmis:student:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['cmis:student:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>

        <el-button
          type="warning"
          plain
          @click="onOpenBatchImport"
          v-hasPermi="['cmis:student:create']"
        >
          <Icon icon="ep:upload" class="mr-5px" />
          导入认领学生
        </el-button>
        <el-button
          type="primary"
          plain
          @click="ClaimableStudent"
          :loading="exportLoading"
          v-hasPermi="['cmis:student:export']"
        >
          <Icon icon="ep:top-right" class="mr-5px" />
          学生转出
        </el-button>

        <!-- <el-button type="danger" @click="handleDeleteMulti" v-hasPermi="['cmis:student:delete']">
          <Icon icon="ep:delete" class="mr-5px" />
          批量删除
        </el-button> -->

        <!-- <el-button
          type="info"
          plain
          @click="openStudentSyncForm"
          v-hasPermi="['cmis:csbusiness:sync-student-data']"
        >
          <Icon icon="ep:upload" class="mr-5px" />
          同步学生
        </el-button>
        <el-button
          type="primary"
          plain
          @click="updateStudentImagesPopup"
          v-hasPermi="['cmis:csbusiness:sync-student-data']"
        >
          <Icon icon="ep:upload" class="mr-5px" />
          上传学生照片
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap :setPadding="false">
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="selectionChange"
      stripe
      :max-height="tableHeight"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="学生姓名" prop="studentName" show-overflow-tooltip />
      <el-table-column label="学籍号" prop="studentCode" show-overflow-tooltip />
      <el-table-column label="学生编号" prop="sort" show-overflow-tooltip />
      <el-table-column label="学校名称" prop="schoolName" show-overflow-tooltip />
      <el-table-column label="机构名称" prop="collegeName" show-overflow-tooltip />
      <el-table-column label="专业名称" prop="majorName" show-overflow-tooltip />
      <el-table-column label="班级名称" prop="classesName" show-overflow-tooltip />
      <el-table-column label="年级 " prop="grade">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CMIS_GRADE_TYPE" :value="scope.row.grade" />
        </template>
      </el-table-column>
      <el-table-column label="口令" prop="openId" show-overflow-tooltip />
      <el-table-column label="性别" prop="sex">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="在校状态" prop="state">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CMIS_STUDENT_STATE" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
        show-overflow-tooltip
      />
      <!-- <el-table-column label="操作" fixed="right" width="100">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['cmis:student:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['cmis:student:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <!-- <StudentForm ref="formRef" @success="getList" /> -->

  <GenerateResultTableDialog ref="generateResultTableDialog" />

  <!-- 导入学生 -->
  <Dialog
    v-model="importState.dialogVisible"
    :title="importState.title"
    width="80%"
    :minHeight="900"
  >
    <ExcelParser
      :tips="importState.tips"
      ref="excelParserRef"
      :importApi="claimableStudentApi.importClaimableStudent"
      :targetTableColumns="importColumns"
      :templateName="importState.title"
    />
    <template #footer>
      <el-button type="primary" @click="onBatchImport()" :loading="importLoading">确 定</el-button>
      <el-button @click="onCancel">取 消</el-button>
    </template>
  </Dialog>

  <!-- <StudentSyncForm ref="studentSyncFormRef" @success="getList" /> -->
  <!-- 上传学生照片 -->
  <!-- <UpdateStudentImagesPopup ref="updateStudentImagesPopupRef" /> -->
  <ClaimableStudentForm ref="ClaimableStudentFormRef" @success="getList" />
</template>

<script setup lang="ts" name="Student">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as claimableStudentApi from '@/api/cmis/claimableStudent'
import ClaimableStudentForm from './ClaimableStudentForm.vue'
// import StudentForm from './StudentForm.vue'
import { useValidator } from '@/hooks/web/useValidator'
// import StudentSyncForm from './StudentSyncForm.vue'
// import UpdateStudentImagesPopup from './UpdateStudentImagesPopup.vue'
const { required } = useValidator()
const form = ref(null)
const { width, height } = useElementSize(form)
const tableHeight = useWindowSize(78 + 76, height)
const message = useMessage() // 消息弹窗
// const { t } = useI18n() // 国际化
import { DICT_TYPE, getDictValuesStr, getIntDictOptions } from '@/utils/dict'
import { ITargetTableColumbnItem } from '@/components/ExcelParser/src/type'

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  studentName: null,
  studentCode: null,
  sex: null,
  grade: null,
  state: null
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const selection = ref()

// const updateStudentImagesPopupRef = ref()
//批量上传学生照片
// const updateStudentImagesPopup = () => {
//   updateStudentImagesPopupRef.value.open()
// }

/** 查询列表 */
const getList = async () => {
  // 接收子组件的数据
  const selectData = selection.value
    ? { ...queryParams, ...selection.value.selectData }
    : { ...queryParams }

  loading.value = true
  try {
    const data = await claimableStudentApi.getStudentPage(selectData)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  selection.value.resetFormData()
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
// const formRef = ref()
// const openForm = (type: string, id?: number) => {
//   formRef.value.open(type, id)
// }

/** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await StudentApi.deleteStudent(id)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await claimableStudentApi.exportStudent(queryParams)
    download.excel(data, '已转出学生.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

//#region 批量导入学生
const importLoading = ref(false)
const excelParserRef = ref<any>()

const importState = reactive({
  tips: [
    '机构名称: 可以是学校名称等',
    '性别编码: ' + getDictValuesStr(DICT_TYPE.SYSTEM_USER_SEX),
    '年级编码: ' + getDictValuesStr(DICT_TYPE.CMIS_GRADE_TYPE)
  ],
  dialogVisible: false,
  title: '导入认领学生'
})

//转出
const ClaimableStudentFormRef = ref()
const ClaimableStudent = () => {
  // console.log('转出')
  ClaimableStudentFormRef.value.open(queryParams)
}

// const extraParameters = ref<ExtraParam[]>([
//   {
//     paramType: 'boolean',
//     paramLabel: '是否覆盖',
//     paramName: 'update'
//   }
// ])

const importColumns = ref<ITargetTableColumbnItem[]>([
  {
    label: '学籍号',
    field: 'studentCode',
    rules: [required('学籍号不能为空')]
  },
  {
    label: '姓名',
    field: 'studentName',
    rules: [required('姓名不能为空')]
  },
  {
    label: '学生编号',
    field: 'sort',
    rules: []
  },
  {
    label: '性别编码',
    field: 'sex',
    rules: [required('性别不能为空')],
    parseRule: {
      dictType: DICT_TYPE.SYSTEM_USER_SEX,
      defaultValue: 3
    }
  },
  {
    label: '口令',
    field: 'openId',
    rules: []
  },
  {
    label: '学校',
    field: 'schoolName',
    rules: [required('学校不能为空')]
  },
  {
    label: '机构名称',
    field: 'collegeName',
    rules: []
  },
  {
    label: '机构编码',
    field: 'collegeCode',
    rules: []
  },
  {
    label: '专业名称',
    field: 'majorName',
    rules: []
  },
  {
    label: '专业编码',
    field: 'majorCode',
    rules: []
  },
  {
    label: '班级名称',
    field: 'classesName',
    rules: [required('班级名称不能为空')]
  },
  {
    label: '班级编码',
    field: 'classesCode',
    rules: []
  },
  {
    label: '年级编码',
    field: 'grade',
    rules: [],
    parseRule: {
      dictType: DICT_TYPE.CMIS_GRADE_TYPE
    }
  }
])

//批量导入
const onOpenBatchImport = () => {
  importState.dialogVisible = true
}

const onBatchImport = async () => {
  importLoading.value = true
  const isSuccess = await excelParserRef.value?.onSubmit()
  console.log('isSuccess', isSuccess)

  if (isSuccess) {
    importLoading.value = false
    ElMessage({
      message: '导入成功',
      type: 'success',
      duration: 1000,
      onClose: () => {
        // importLoading.value = false
        importState.dialogVisible = false
        getList()
      }
    })
  } else {
    importLoading.value = false
    return
  }
  importLoading.value = false
  importState.dialogVisible = false
}

const onCancel = () => {
  importState.dialogVisible = false
  importLoading.value = false
}

//#endregion

const listOfIds = ref([]) //选中的设备

// 选中设备
const selectionChange = (val: any) => {
  listOfIds.value = val.map((item: any) => item.id)
}

// 批量删除操作
// const handleDeleteMulti = async () => {
//   if (listOfIds.value.length > 0) {
//     try {
//       // 批量删除的二次确认
//       await message.delConfirm()
//       // 发起批量删除
//       const res = await StudentApi.batchDeleteStudent(listOfIds.value)
//       message.success(t('common.delSuccess'))
//       // 刷新列表
//       await getList()
//       openGenerateResultTableDialog(res)
//     } catch {}
//   } else {
//     message.warning(t('请选择要删除的学生!'))
//   }
// }

/**
 * 生成后回显的内容
 */
// const labelMap = ref({
//   schoolName: '学校名称',
//   collegeName: '机构名称',
//   classesName: '班级名称',
//   studentName: '学生姓名',
//   studentCode: '学生编号',
//   msg: '信息'
// })
// const generateResultTableDialog = ref()
// const openGenerateResultTableDialog = (res) => {
//   generateResultTableDialog.value.open(labelMap.value, res)
// }

// const studentSyncFormRef = ref()
// const openStudentSyncForm = () => {
//   studentSyncFormRef.value.open()
// }

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
